//
//  YUYARegisterViewController.m
//  com.yigu.yuya
//
//  Created by hxp on 16/3/2.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIRegisterViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "YAYIRegisterPwdViewController.h"
#import "YAYAgreementViewController.h"
#import <MessageUI/MessageUI.h>


@interface YAYIRegisterViewController ()<UITextFieldDelegate>

@property (strong,nonatomic)UITextField *accountTextField;
@property (strong,nonatomic)UITextField *verifyCodeTextField;
@property (strong,nonatomic)UIButton *verifyBtn;
@property (strong,nonatomic)UIButton *checkBtn;
@property (strong,nonatomic)UILabel  *content;
@property (strong,nonatomic)UIButton *nextBtn;
@property (strong,nonatomic)UILabel  *textFieldBackground;
@property (strong,nonatomic)UILabel  *seprateLine;
@property (nonatomic,strong)UIButton *backBtn;
@property (strong,nonatomic)UILabel  *account;
@property (strong,nonatomic)UILabel  *verify;
@property (strong,nonatomic)NSTimer  *timer;
@property (assign,nonatomic)NSInteger s;

@property (assign, nonatomic) BOOL isHaveGetVerificationCode;
@property (assign, nonatomic) NSInteger vertificationCodeTimeStamp;

@end
@implementation YAYIRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.s = 60;
    self.view.backgroundColor = [UIColor  whiteColor];
    self.title = self.titleStr;

    [self  createViews];
}


-(void)createViews{
    if (self.textFieldBackground == nil) {
        self.textFieldBackground = [UILabel new];
        self.textFieldBackground.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.textFieldBackground.layer.borderWidth = 0.5;
        self.textFieldBackground.layer.masksToBounds = YES;
        self.textFieldBackground.layer.cornerRadius = 2;
        [self.view addSubview:self.textFieldBackground];
    }
    [self.textFieldBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(32 + 64);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - (17 * 2), 44 * 2));
    }];

    if (self.accountTextField == nil) {
        self.accountTextField = [UITextField new];
        self.accountTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.accountTextField.placeholder = @"手机号";
        self.accountTextField.font = [UIFont systemFontOfSize:14];
        self.accountTextField.delegate = self;
        [self.view addSubview:self.accountTextField];
    }
    [self.accountTextField  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.textFieldBackground.mas_top).with.offset(2);
        make.left.equalTo(@25);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - (25 * 2), 40));
    }];
    
    
    if (self.seprateLine == nil) {
        self.seprateLine = [UILabel  new];
        self.seprateLine.backgroundColor = [UIColor lightGrayColor];
        [self.view addSubview:self.seprateLine];
        
    }
    [self.seprateLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@17);
        make.centerY.mas_equalTo(self.textFieldBackground);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - 17 * 2, 0.5));
    }];

    
    if (self.verifyCodeTextField == nil) {
        self.verifyCodeTextField = [UITextField  new];
        self.verifyCodeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.verifyCodeTextField.placeholder = @"验证码";
        self.verifyCodeTextField.font = [UIFont systemFontOfSize:13];
        self.verifyCodeTextField.delegate = self;
        [self.view addSubview:self.verifyCodeTextField];
    }
    [self.verifyCodeTextField  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.accountTextField);
        make.top.mas_equalTo(self.seprateLine.mas_bottom).with.offset(2);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - (17 * 2), 40));
    }];
    
    
    if (self.verifyBtn == nil) {
        self.verifyBtn = [UIButton  buttonWithType: UIButtonTypeCustom];
        [self.verifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.verifyBtn.titleLabel.font = [UIFont  systemFontOfSize:14];
        self.verifyBtn.frame = CGRectMake(0, 0, 100, 10);
        [self.verifyBtn setTitleColor:[UIColor  colorWithRed:83/255.0 green:165/255.0 blue:243/255.0 alpha:1] forState:UIControlStateNormal];
        self.verifyCodeTextField.rightView = self.verifyBtn;
        [self.verifyBtn addTarget:self action:@selector(verifyAction:) forControlEvents:UIControlEventTouchUpInside];
        self.verifyCodeTextField.rightViewMode = UITextFieldViewModeAlways;
    }
    
    
    if (self.checkBtn == nil) {
        self.checkBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [self.checkBtn setBackgroundImage:[UIImage  imageNamed:@"selected_button_normal"] forState:UIControlStateNormal];
        [self.view addSubview:self.checkBtn];
    }
    [self.checkBtn  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.textFieldBackground.mas_bottom).with.offset(14);
        make.left.equalTo(@17);
        make.size.mas_equalTo(CGSizeMake(13, 13));
    }];
    
    
    if (self.content == nil) {
        self.content = [UILabel  new];
        self.content.font = [UIFont  systemFontOfSize:13];
        NSMutableAttributedString *atring = [[NSMutableAttributedString  alloc] initWithString: @"我同意"];
        [atring addAttributes:@{NSForegroundColorAttributeName:[UIColor  colorWithRed:81/255.0 green:80/255.0 blue:80/255.0 alpha:1]} range:NSMakeRange(0, 3)];
//        [atring addAttribute:NSForegroundColorAttributeName value:[UIColor  colorWithRed:83/255.0 green:165/255.0 blue:243/255.0 alpha:1] range:NSMakeRange(3, 10)];
        self.content.attributedText = atring;
        [self.view addSubview:self.content];
    }
    [self.content mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.checkBtn);
        make.left.mas_equalTo(self.checkBtn.mas_right).with.offset(9);
//        make.size.mas_equalTo(CGSizeMake(180, 12));
    }];
    
    UIButton *agreementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [agreementBtn setTitle:@"《雅同用户服务协议》" forState:UIControlStateNormal];
    agreementBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [agreementBtn setTitleColor:YAYIColor(83, 165, 243) forState:UIControlStateNormal];
    [agreementBtn setTitleColor:YAYIColor(55, 93, 128) forState:UIControlStateHighlighted];
    agreementBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [agreementBtn addTarget:self action:@selector(onAgreementBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:agreementBtn];
    [agreementBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.content);
        make.left.mas_equalTo(self.content.mas_right).offset(0);
        make.size.mas_equalTo(CGSizeMake(120, 12));
    }];
    
    
    if (self.nextBtn == nil) {
        self.nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.nextBtn setBackgroundImage:[UIImage  imageNamed:@"register_button_normal"] forState:UIControlStateNormal];
        [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [self.nextBtn setTitleColor:[UIColor  whiteColor] forState:UIControlStateNormal];
        [self.nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.nextBtn];
    }
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.checkBtn.mas_bottom).with.offset(93);
        make.left.equalTo(@17);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - 17 * 2, 45));
    }];
    
    if ([self.titleStr isEqualToString:@"密码重置"]) {
        [self.checkBtn setHidden:YES];
        [self.content setHidden:YES];
    }
}



-(void)count:(NSTimer *)timer
{
    
    self.s -= 1;
    [self.verifyBtn setTitle:[NSString stringWithFormat:@"%lds",self.s] forState:UIControlStateNormal];
    [self.verifyBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    
    if (self.s == 0) {
        self.s = 60;
        [self.timer invalidate];
        [self.verifyBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        [self.verifyBtn setTitleColor:[UIColor  colorWithRed:83/255.0 green:165/255.0 blue:243/255.0 alpha:1] forState:UIControlStateNormal];
        self.timer = nil;
        self.verifyBtn.enabled = YES;
    }
}


- (void)resignAll
{
    [self.accountTextField resignFirstResponder];
    [self.verifyCodeTextField resignFirstResponder];
}


-(void)createControll:(NSString *)title{
    
    // 停止定时器
    self.s = 60;
    [self.timer invalidate];
    [self.verifyBtn setTitle:@"重新获取" forState:UIControlStateNormal];
    [self.verifyBtn setTitleColor:[UIColor  colorWithRed:83/255.0 green:165/255.0 blue:243/255.0 alpha:1] forState:UIControlStateNormal];
    self.timer = nil;
    
    YAYIRegisterPwdViewController *pwdView = [YAYIRegisterPwdViewController new];
    //    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:pwdView];
    pwdView.titleStr = title;
    pwdView.mobile = self.accountTextField.text;
    [self.navigationController pushViewController:pwdView animated:YES];
}


#pragma mark - 获取数据
/**
 *  检查手机号码和角色是否一致
 */
-(void)checkMobileAnRole
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"mobile"] = self.accountTextField.text;
    param[@"role"] = @(2);
    
    [YAYINetWorking getWithURL:checkMobileAndRole_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                YAYILog(@"检查手机号码和角色是否一致：%@",dict);
                
                // 0:当前用户不存在，请先注册！1:当前用户和角色不一致 2:当前用户和角色一致
                NSInteger type = [dict[@"data"] integerValue];
                if (type == 1) {
                    
                    self.verifyBtn.enabled = YES;
                    NSString *message = dict[@"message"];
                    [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", message]];
                }else{
                    
                    if (type == 0 && ![self.title isEqualToString:@"注册"]) {
                        self.verifyBtn.enabled = YES;
                        NSString *message = dict[@"message"];
                        [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", message]];
                        return;
                    }
                    
                    [self.verifyCodeTextField becomeFirstResponder];
                    [self getVerificationCode];
                }
            }
            
        }else{
            
            NSDictionary *erroDict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"erro:%@", erroDict);
        }
    }];
}


/**
 *  获取验证码
 */
-(void)getVerificationCode{
    
//    [self createHudView:[NSString stringWithFormat:@"验证码已发送到%@", self.accountTextField.text]];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"mobile"] = self.accountTextField.text;
    param[@"role"] = @(2);
    
    [YAYINetWorking getWithURL:captcha_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            
            YAYILog(@"获取验证码：%@",dict);
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n验证码已发送到\n%@\n", self.accountTextField.text]];
                
                self.isHaveGetVerificationCode = YES;
                self.vertificationCodeTimeStamp = [[NSDate date] timeIntervalSince1970];
                
                // 启动定时器
                self.verifyCodeTextField.font = [UIFont systemFontOfSize:14];
                
                // 修改按钮状态
                [self.verifyBtn setTitle:@"60" forState:UIControlStateNormal];
                [self.verifyBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                self.verifyBtn.enabled = NO;
                
                if (self.timer == nil) {
                    self.timer = [NSTimer  scheduledTimerWithTimeInterval:1 target:self selector:@selector(count:) userInfo:nil repeats:YES];
                }
            }else{
            
                self.verifyBtn.enabled = YES;
                NSString *message = dict[@"message"];
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", message]];
            }
           
        }else{
        
            NSDictionary *erroDict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"erro:%@", erroDict);
//            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n验证码已发送到\n%@\n", self.accountTextField.text]];
        }
    }];
}

/**
 * 检查手机号的唯一性
 */
-(void)checkMobile:(NSString *)title
{
    if ([@"新密码" isEqualToString:title]) {
        
        
    }else{
        
        [YAYINetWorking getWithURL:checkMobile_url param:@{@"mobile":self.accountTextField.text} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
            
            YAYILog(@"检查号码唯一性返回：%@", dict);
            
            if ([dict[@"status"] isEqualToString:@"error"]) {
                
                self.verifyBtn.enabled = YES;
//                [self createHudView:dict[@"message"]];
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
                return ;
                
            }else{
                
                [self.verifyCodeTextField becomeFirstResponder];
                // 获取验证码
                [self getVerificationCode];
            }
        }];
    }
}





/** 对验证码进行校验
 *
 */
-(void)verifyCaptcha :(NSString *)title{
    
    NSDictionary *dict = @{@"captcha":self.verifyCodeTextField.text};
    
    [YAYINetWorking getWithURL:verifyCaptcha_url param:dict finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            
            NSString *message = dict[@"message"];
            NSString *status = dict[@"status"];
            if ([status isEqualToString:@"error"]) {
                
//                [self createHudView:message];
                [SVProgressHUD showErrorWithStatus:message];
                return ;
            }else{
                
                [SVProgressHUD showSuccessWithStatus:message];
                [self createControll:title];
            }
            
            
        }else {
            YAYILog(@"dict:%@ error:%@", dict, error);
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"dict:%@", dict);
            
            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
        }
        
    }];
}


#pragma mark - 响应事件
-(void)backAction:(UIButton *)sender{
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
}


-(void)nextAction:(UIButton *)sender
{
    [self resignAll];
    
    if([self.accountTextField.text isEqualToString:@""]||self.accountTextField.text.length == 0)
    {
//        [self createHudView:@"手机号不能为空"];
        [SVProgressHUD showImage:nil status:@"\n\n手机号不能为空\n\n"];
        return;
    }else if (self.verifyCodeTextField.text.length == 0) {
        
//        [self createHudView:@"验证码不能为空"];
        [SVProgressHUD showImage:nil status:@"\n\n验证码不能为空\n\n"];
        return;
    }
    
    // 判断是否获取验证码
    if (!self.isHaveGetVerificationCode) {
        
        [SVProgressHUD showImage:nil status:@"\n\n请先获取验证码\n\n"];
        return;
    }
    
    // 判断验证码是否超时，超时时间5分钟
    NSInteger nowTimeStamp = [[NSDate date] timeIntervalSince1970];
    
    if ((nowTimeStamp - self.vertificationCodeTimeStamp) / 60.0 > 5) {
        
        [SVProgressHUD showImage:nil status:@"\n\n验证码已过期\n\n"];
        return;
    }
    
    NSString *nexCtlTitle = @"注册";
    if ([self.titleStr isEqualToString:@"密码重置"]) {
        nexCtlTitle = @"新密码";
    }
    [self verifyCaptcha:nexCtlTitle];
}


/**
 * 获取验证码, 获取验证码前判断1.手机号合法性 2.手机号是否重复
 */
-(void)verifyAction:(UIButton *)sender{
    
    sender.enabled = NO;
    
    // 1. 验证手机号的合法性
    NSString *checkMobileMsg = [NSString valiMobile:self.accountTextField.text];
    if(checkMobileMsg != nil)
    {
        
        [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", checkMobileMsg]];
        return;
    }
    
    // 2. 验证手机号是否重复
    if ([self.titleStr isEqualToString:@"密码重置"]) {
        
        // 检查手机号码和角色是否一致
        [self checkMobileAnRole];
    }else{
        [self checkMobile:@"注册"];
    }
}


- (void)onAgreementBtnClick:(UIButton *)sender
{

    YAYAgreementViewController *agreementVc = [[YAYAgreementViewController alloc] init];
    YAYINavigationController *nav = [[YAYINavigationController alloc] initWithRootViewController:agreementVc];
    [self presentViewController:nav animated:YES completion:nil];
}



#pragma mark 工具方法
-(void)createHudView:(NSString *)msg
{
    YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
    [self.view.window addSubview:hud];
    [hud setMessage:msg];
    
    [hud removeFromSuperview:YES time:1.0 isHinden:YES];
}


#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField  resignFirstResponder];
    return YES;
}

@end
